package preprocessing;

import weka.core.Attribute;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ConverterUtils;

public class Zsocre {

    static boolean Classify(Instances instances){ //按照不同属性进行分类
        int len=instances.numInstances(),attribute=instances.numAttributes()-1,i,j;
        boolean success;
        double [][]data=new double[attribute][len];
        double sum,mean,deviaction_sum;
        for(i=0;i<attribute;i++){
            sum=0;
            for(j=0; j<len;j++){
                data[i][j]=instances.instance(j).value(i);
                sum+=data[i][j];
            }
            mean=sum/len;
            deviaction_sum=StandardDeviaction(data[i],mean,len);
            success=Normalize(instances,deviaction_sum,mean,i,len);
            if(success==true){
                System.out.println(instances.attribute(i).name()+"归一化成功");
            }
        }
        return true;
    }

    static double StandardDeviaction(double []data,double mean,int len){
        double deviaction_sum=0,sum=0;
        for(int j=0;j<len;j++){
            sum+=Math.pow(data[j]-mean,2);
        }
        deviaction_sum=Math.sqrt(sum/(len-1));
        return deviaction_sum;
    }

    public static boolean Normalize(Instances instances,double deviaction_sum,double mean,int attribute,int len){
        double data;
        for(int j=0;j<len;j++) {
            data = (instances.instance(j).value(attribute) - mean) / deviaction_sum;
            instances.instance(j).setValue(attribute, data);
        }
        return true;
    }

    public static void printAttribute(Instances instances)
    {
        int numOfAttributes = instances.numAttributes();
        for(int i = 0; i < numOfAttributes ;++i)
        {
            Attribute attribute = instances.attribute(i);
            System.out.print(attribute.name() + " ");
        }
        System.out.println();
        //打印实例
        int numOfInstance = instances.numInstances();
        for(int i = 0; i < numOfInstance; ++i)
        {
            Instance instance = instances.instance(i);
            System.out.print(instance.toString() + " " + "\n");
        }
    }

    public static void main(String[] args) throws Exception {
        boolean success;
        ConverterUtils.DataSource source = new ConverterUtils.DataSource("/home/tang/appdata/weka-3-8-4/data/iris.arff");
        Instances instances= source.getDataSet();
        success=Classify(instances);
        if(success==true){
            System.out.println("数据归一化完成,结果如下：");
            printAttribute(instances);
        }
    }
}
